package com.login.sotoken.utils;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.secure.totp.SaTotpUtil;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @Description AES加密
 * @Author xiaohuang
 * @Date 2025/8/15
 */
@Slf4j
public class AseUtil {
    // 定义秘钥和明文
    private final static String KEY = "123456";
    private final static String TEXT = "sa-token";

    /**
     * 获取秘钥
     *
     * @param password
     * @return
     * @throws NoSuchAlgorithmException
     */
    private static SecretKeySpec getSecretKey(final String password) throws NoSuchAlgorithmException {
        KeyGenerator kg = KeyGenerator.getInstance("AES");
        //获取SHA1PRNG伪随机数生成器
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        //将实际密码作为伪随机数生成器的种子
        random.setSeed(password.getBytes());
        //利用伪随机数生成器生成128位的密钥，能确保解密时生成的密钥的一致性
        kg.init(128, random);
        SecretKey secretKey = kg.generateKey();
        return new SecretKeySpec(secretKey.getEncoded(), "AES");
    }



    public static void main(String[] args) {
        //1.AES对称加密
        //加密
        String s = SaSecureUtil.aesEncrypt(KEY, TEXT);
        log.info("AES加密：{}",s);
        //解密
        String ciphertext  = SaSecureUtil.aesDecrypt(KEY, s);
        log.info("AES解密：{}",ciphertext);
        //2.TOTP验证器
        //2.1生成密钥
        String secretKey = SaTotpUtil.generateSecretKey();
        log.info("TOTP密钥：{}",secretKey);
        //生成扫码字符串
        String qeString = SaTotpUtil.generateGoogleSecretKey("zhangsan", secretKey);
        log.info("TOTP二维码：{}",qeString);
        //计算当前 TOTP 码
        String code = SaTotpUtil.generateTOTP(secretKey);
        log.info("当前时间戳对应的TOTP码：{}",code);
        //验证码验证
        boolean b = SaTotpUtil.validateTOTP(secretKey, code, 1);
        log.info("验证码验证：{}",b);

    }

}
